﻿using System;
using System.Web;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using Word = Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Collections;
using Model;

using IntraVision.Web;
using IntraVision.Web.Toolkit;

namespace NotarialService.Classes
{
    /// <summary>
    /// Summary description for WordReport
    /// </summary>
    public static class WordReport
    {
        private static string GenerateClientsDescription(List<IClient> clients)
        {
            var sb = new StringBuilder();

            foreach (var c in clients)
                sb.AppendLine(String.Format("{0} {1}", c.Name, (Client.CheckIsNatural(c.Cid)) ? ((Person)c).Phone : "").Trim());

            return sb.ToString().Trim();
        }

        public static string GetReportFileName(Order order, List<IClient> clients, List<IClient> responsibles, string folderPath, string templateName)
        {
            Word.Application wordapp = null;
            Word.Documents worddocuments = null;
            Word.Document worddocument = null;
            Word.Paragraphs wordparagraphs = null;
            Word.Paragraph wordparagraph = null;
            Word.Range wordrange = null;
            Word.Table wordtable = null;

            string newFileName = string.Format("квитанция_по_заявке_№_{0}_{1}.doc", order.Id, DateTime.Now).Replace(' ','_').Replace(':','_');

            try
            {
                wordapp = new Word.Application();
                Object template = Path.Combine(folderPath, templateName);
                Object newTemplate = true;
                Object documentType = Word.WdNewDocumentType.wdNewBlankDocument;
                Object visible = false;
                worddocument = new Word.Document();
                worddocument = wordapp.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);
                worddocuments = wordapp.Documents;
                worddocument.Activate();

                FindAndReplaceWord(wordapp, "{{id}}", order.Id.ToString(), false);
                FindAndReplaceWord(wordapp, "{{notarialactionname}}", order.NotarialAction.FullName, false);
                FindAndReplaceWord(wordapp, "{{doccount}}", order.DocCount.ToString(), false);
                FindAndReplaceWord(wordapp, "{{copycount}}", order.CopyCount.ToString(), false);
                FindAndReplaceWord(wordapp, "{{isnotforregistration}}", order.IsNotForRegistration ? "Да":"Нет", false);
                FindAndReplaceWord(wordapp, "{{clients}}", GenerateClientsDescription(clients), false);
                FindAndReplaceWord(wordapp, "{{responsibles}}", GenerateClientsDescription(responsibles), false);
                FindAndReplaceWord(wordapp, "{{description}}", order.Description, false);
                FindAndReplaceWord(wordapp, "{{deadline}}", order.Deadline.ToDateString(), false);

                #region "Сохранить как..." обработанный шаблон
                Object fileName1 = Path.Combine(Path.Combine(folderPath, "Temp"), newFileName);
                Object fileFormat = Word.WdSaveFormat.wdFormatDocument;
                Object lockComments = false;
                Object password = "";
                Object addToRecentFiles = false;
                Object writePassword = "";
                Object readOnlyRecommended = false;
                Object embedTrueTypeFonts = false;
                Object saveNativePictureFormat = false;
                Object saveFormsData = false;
                Object saveAsAOCELetter = Type.Missing;
                Object encoding = Type.Missing;
                Object insertLineBreaks = Type.Missing;
                Object allowSubstitutions = Type.Missing;
                Object lineEnding = Type.Missing;
                Object addBiDiMarks = Type.Missing;
                worddocument.SaveAs(ref fileName1,
                    ref fileFormat, ref lockComments,
                    ref password, ref addToRecentFiles, ref writePassword,
                    ref readOnlyRecommended, ref embedTrueTypeFonts,
                    ref saveNativePictureFormat, ref saveFormsData,
                    ref saveAsAOCELetter, ref encoding, ref insertLineBreaks,
                    ref allowSubstitutions, ref lineEnding, ref addBiDiMarks);
                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                NAR(wordtable);
                NAR(wordrange);
                NAR(wordparagraphs);
                NAR(wordparagraph);
                NAR(worddocument);
                NAR(worddocuments);
                Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
                Object originalFormat = Word.WdOriginalFormat.wdWordDocument;
                Object routeDocument = Type.Missing;
                if (wordapp != null)
                    ((Word._Application)wordapp).Quit(ref saveChanges, ref originalFormat, ref routeDocument);
                NAR(wordapp);
                GC.Collect();
            }
            return newFileName;
        }

        #region FindAndReplaceWord() Найти и заменить все слова
        /// <summary>
        /// Находит и переименовывает слово
        /// </summary>
        /// <param name="wordapp">Word application</param>
        /// <param name="findWord">Слово, которое нужно найти</param>
        /// <param name="rePlace">Слово, на которое заменяем</param>
        /// <param name="matchCase">Чувствительность к регистру</param>
        private static void FindAndReplaceWord(Word.Application wordapp, string findWord, string rePlace, Object matchCase)
        {
            //переводим курсор в начало документа
            Object unit = Word.WdUnits.wdStory;
            Object extend = Word.WdMovementType.wdMove;
            wordapp.Selection.HomeKey(ref unit, ref extend);
            //ищем и заменяем все слова
            Object findText = findWord;
            Object matchWholeWord = true;
            Object matchWildcards = false;
            Object matchSoundsLike = false;
            Object matchAllWordForms = false;
            Object forward = true;
            Object wrap = Word.WdFindWrap.wdFindContinue;
            Object format = false;
            Object replaceWith = rePlace;
            Object replace = Word.WdReplace.wdReplaceAll;
            Object matchKashida = false;
            Object matchDiacritics = false;
            Object matchAlefHamza = false;
            Object matchControl = false;
            wordapp.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord,
                ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms, ref forward,
                ref wrap, ref format, ref replaceWith, ref replace, ref matchKashida,
                ref matchDiacritics, ref matchAlefHamza, ref matchControl);
        }
        #endregion

        #region NAR() Освобождаем память от COM-объектов
        private static void NAR(object o)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
            }
            catch { }
            finally
            {
                o = null;
            }
        }
        #endregion
    }
}
